/*
 * Copyright (c) 2013-2018 上海汇数数据. All rights reserved.
 * @(#) FieldError.java 2018-08-08 17:51
 */

package cn.jh.common.core.ret;

import cn.jh.common.core.base.ToStrings;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.inferred.freebuilder.FreeBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.Serializable;


/**
 * @author Fuchun
 * @since 1.0
 */
@FreeBuilder
@JsonDeserialize(builder = FieldError.Builder.class)
public interface FieldError extends Serializable {

    static FieldError from(@NotNull org.springframework.validation.FieldError fe) {
        Builder feb = new Builder(fe.getField())
                .setCode(fe.getCode())
                .setRejectedValue(fe.getRejectedValue())
                .setMessage(fe.getDefaultMessage());
        return feb.build();
    }

    static Builder with(String field) {
        return new Builder(field);
    }

    String getField();

    @Nullable
    String getCode();

    @Nullable
    String getMessage();

    @Nullable
    Object getRejectedValue();

    class Builder extends FieldError_Builder {
        public Builder() {
        }

        public Builder(String field) {
            setField(field);
        }

        @Override
        public Builder setRejectedValue(@Nullable Object rejectedValue) {
            Object newValue = null;
            if (rejectedValue != null) {
                if (rejectedValue instanceof String) {
                    String value = (String) rejectedValue;
                    if (value.length() > 30) {
                        newValue = ToStrings.ellipsis(value, 30);
                    }
                }
                if (newValue == null) {
                    newValue = rejectedValue;
                }
            }
            return super.setRejectedValue(newValue);
        }
    }
}
